package apptoko.com;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Toast;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.download.http.HttpLa;
import apptoko.com.download.http.HttpLa.LocationResult;
import apptoko.com.event.Event.ClientUpdateNameNotFoundEvent;
import apptoko.com.event.Event.GetEnaCStatusEvent;
import apptoko.com.event.Event.GetTorStatusEvent;
import apptoko.com.event.Event.LatestVersionEvent;
import apptoko.com.event.Event.RequestUpdateFailEvent;
import apptoko.com.fragment.CategoryFragment;
import apptoko.com.fragment.HomeListFragment;
import apptoko.com.model.ApptokoUpdateData;
import apptoko.com.network.DownloadUpdateTask;
import apptoko.com.util.CommonUtils;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.view.AlertDialogManager;

import com.appota.asdk.commons.AccessTokenUtil;
import apptoko.com.R;
import com.astuetz.viewpager.extensions.PagerSlidingTabStrip;

import de.greenrobot.event.EventBus;

public class HomeActivity extends BaseActivity  implements apptoko.com.network.IDownloadUpdateCallback{
	
	private ISlidingMenuClosed menuClosedListener;
	private static ViewPager viewPager;
	private Resources res;
	private HomeFragmentAdapter adapter;
	private boolean doubleBackToExit = false;
	private String language="";
	private ProgressDialog progressLoading;
	public static final String KEY_UPDATE_DATA = "_update_data";
	private BackgroundTasks bgTask;
	private String updateUri = "";
	private String countryCode;
	public HomeActivity() {
		super(R.string.app_name);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EventBus.getDefault().unregister(this);
		EventBus.getDefault().register(this);
		Log.e("","onStartHome");
	}
	
	private void checkUpdateDaily(){
		SharedPreferences shared= getSharedPreferences("system_pre", MODE_PRIVATE);
		String previousUpdate=shared.getString("_check_update_", "1/1/2013");
		DateFormat dateFormar = new SimpleDateFormat("dd/MM/yyyy");
		Date now = null;
		try {
			now = new SimpleDateFormat("dd/MM/yyy", Locale.ENGLISH).parse(previousUpdate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
//		String preCheckUpdate = dateFormar.format(now);
//		Log.e("preCheckUpdate", "preCheckUpdate: "+preCheckUpdate);
		long unixTime=now.getTime()/1000;
		if(CommonUtils.checkUpdateNoti(CommonUtils.convertUnixTime(Integer.parseInt(String.valueOf(unixTime))))){
			now = new Date();
			shared.edit().putString("_check_update_", dateFormar.format(now)).commit();
			//start check update
			if(progressLoading!=null && !progressLoading.isShowing()){
				progressLoading.setMessage(getResources().getString(R.string.checking_update));
				progressLoading.show();
			}
			doCheckUpdate();
			checkTor();
		}else{
			checkTor();
		}
	}
	public static void setIndex(int indexe){
		viewPager.setCurrentItem(indexe);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.e("","onPauseHome");
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Utils.uninstallOldVersion(this);
		language= UILApplication.getInstance().getConfig().locale.getLanguage();
		Log.e("Language","Language: "+language);
		setSlidingActionBarEnabled(true);
		bgTask=new BackgroundTasks(this);
		if(AccessTokenUtil.getInstance().init(this).getSavedAccessToken()!=null && !TextUtils.isEmpty(AccessTokenUtil.getInstance().init(this).getSavedAccessToken())){
			((AppStoreVnApplication)this.getApplication()).setAccessToken(AccessTokenUtil.getInstance().init(this).getSavedAccessToken());
		}else{
			AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(Constants.DEFIN_ACCESSTOKEN);
			((AppStoreVnApplication)this.getApplication()).setAccessToken(Constants.DEFIN_ACCESSTOKEN);
		}
		progressLoading=new ProgressDialog(this);
		progressLoading.setMessage(getResources().getString(R.string.take_time));
		progressLoading.setCancelable(false);
		progressLoading.show();
		bgTask.checkEnaC();
		initView();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				viewPager.setCurrentItem(2);
			}
		}, 1000);
//		getLA();
	}

	private void doCheckUpdate() {
		if(isOnline()){
//			countryCode = Utils.getFirstStaticCountryCode(this);
//			if(countryCode.equalsIgnoreCase("fi")){
				checkForUpdate();
//			}
			
		}else{
			AlertDialogManager am = new AlertDialogManager(this);
			am.showPositiveDialog(R.string.no_internet, R.string.retry, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					countryCode = Utils.getFirstStaticCountryCode(HomeActivity.this);
					if(countryCode.equalsIgnoreCase("fi")){
						checkForUpdate();
					}
				}
			});
		}
	}
	public static final int REQUEST_CODE = 99;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){
			if(TextUtils.isEmpty(updateUri)){
				updateUri = "market://details?id=apptoko.com";
			}
			if(updateUri.startsWith("market")){
				try {
				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(updateUri)));
				} catch (android.content.ActivityNotFoundException anfe) {
				}
			}else{
				DownloadUpdateTask task = new DownloadUpdateTask(this);
				task.setDownloadCallback(this);
				task.execute(updateUri);
			}
			
		}else{
			bgTask.getCategories(Utils.getStaticAccessToken(this), 2, "app");
		}
	}
	
	
	private Handler handler=new Handler();
	private boolean isRooted;
	private void initView() {
		// TODO Auto-generated method stub
		Log.e("", "intit view ");
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.action_bar_home);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
		res = getResources();
		
		viewPager = (ViewPager) findViewById(R.id.pager);
		
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
		int pageMargin = dm.widthPixels / 48;
		adapter = new HomeFragmentAdapter(getSupportFragmentManager()); 
		viewPager.setOffscreenPageLimit(6);
		viewPager.setPageMargin(pageMargin);
		viewPager.setPageMarginDrawable(R.drawable.bg_pagemargin_xml);
		viewPager.setAdapter(adapter);
//		viewPager.setCurrentItem(1);
		PagerSlidingTabStrip indicator = (PagerSlidingTabStrip) findViewById(R.id.indicator);
        indicator.setViewPager(viewPager);
        indicator.setIndicatorColorResource(R.color.indicator_color);
        int pixelSize = (int) (14 * dm.scaledDensity); 
        indicator.setTextSize(pixelSize);
//        ContentNetworkInterface.getInstance().init(this).getTopContent("2", 0, "03cea4ee604e07b241c4c097feae3274", 2, 0, getVolleySuccessListener(), getVolleyErrorListener());
//        new GetTopAsync("Hot","android_" + ContentNetworkInterface.getAppVersion(this),Utils.isTablet(this)?"":"",0,2,0).execute();
	}
	
	@Override
	protected void onResume(){
		UILApplication instance=UILApplication.getInstance();
		getBaseContext().getResources().updateConfiguration(instance.getConfig(),getBaseContext().getResources().getDisplayMetrics());
		if(language.equals(UILApplication.getInstance().getConfig().locale.getLanguage())){
			super.onResume();
			doubleBackToExit = false;
		}else{
			super.onResume();
			initView();
			language= UILApplication.getInstance().getConfig().locale.getLanguage();
			doubleBackToExit = false;
		}
	}
	
	@Override
	public void onBackPressed(){
//		if(viewPager.getCurrentItem() == 0){
			if(doubleBackToExit){
				super.onBackPressed();
//				Exchanger.showFinishScreen(this, null, false);
				return;
			}
			this.doubleBackToExit = true;
		    Toast.makeText(this, R.string.exit_press_back_twice_message, Toast.LENGTH_SHORT).show();
		    new Handler().postDelayed(new Runnable() {
	            @Override
	            public void run() {
	            	doubleBackToExit = false;
	            }
	        }, 3000);
//		} else {
//			viewPager.setCurrentItem(0);
//		}
	}
	
	public void onEventMainThread(ClientUpdateNameNotFoundEvent event){
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
	}
	
	public void onEventMainThread(LatestVersionEvent event){
		Log.e("latest","latest");
//		Toast.makeText(this, "Country code : "+event.getCountryCode(), Toast.LENGTH_LONG).show();
		SharedPreferences shared= getSharedPreferences("system_pre", MODE_PRIVATE);
		shared.edit().putString(Constants.COUNTRY_CODE, event.getCountryCode()).commit();
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
	}
	public void onEventMainThread(ApptokoUpdateData data){
//		Toast.makeText(this, "Country: "+data.getCountryCode(), Toast.LENGTH_LONG).show();
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
		SharedPreferences shared= getSharedPreferences("system_pre", MODE_PRIVATE);
		shared.edit().putString(Constants.COUNTRY_CODE, data.getCountryCode()).commit();
		updateUri = data.getUpdateUrl();
		if(data.isForce()){
			try {
				AlertDialog.Builder builder=new Builder(this);
				builder.setMessage(Html.fromHtml(data.getMessContent())).setTitle(data.getMessTitle());
				builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=apptoko.com")));
					    finish();
					}
				});
				builder.setCancelable(false);
				builder.show();
			} catch (android.content.ActivityNotFoundException anfe) {
			}
		} else {
			Intent showUpdate = new Intent(this, PopupUpdateActivity.class);
			Bundle bundle = new Bundle();
			bundle.putBoolean("fromAbout", false);
			bundle.putSerializable(HomeActivity.KEY_UPDATE_DATA, data);
			showUpdate.putExtras(bundle);
			startActivityForResult(showUpdate, REQUEST_CODE);
		}
	}
	
	public void setISlidingMenuListener(ISlidingMenuClosed l){
		this.menuClosedListener = l;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}
	
	public void toggleMenu(){
		toggle();
	}

	@Override
	public void onClosed() {
		// TODO Auto-generated method stub
		if(menuClosedListener != null){
			menuClosedListener.onSlideMenuClosed();
			menuClosedListener = null;
		}
	}
	
	public interface ISlidingMenuClosed{
		public void onSlideMenuClosed();
	}
	
	private class HomeFragmentAdapter extends FragmentStatePagerAdapter {

		protected String[] TITLE = new String[] {res.getString(R.string.category),res.getString(R.string.newsfeed), res.getString(R.string.hot_app), res.getString(R.string.top_new), res.getString(R.string.top_download)};

		public HomeFragmentAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			if(position == 0){
				CategoryFragment catFrag = new CategoryFragment();
				Bundle b = new Bundle();
				b.putString(Constants.STORE_KEY, "apps");
				catFrag.setArguments(b);
				return catFrag;
			} 
			else if(position==1){
				NewsFeedActivity news = new NewsFeedActivity();
				Bundle b = new Bundle();
				b.putString(Constants.STORE_KEY, "news");
				news.setArguments(b);
				return news;
			}
			else{
				HomeListFragment listFragment = new HomeListFragment();
				Bundle bundle = new Bundle();
				bundle.putString(Constants.TOP, TITLE[position]);
				bundle.putString(Constants.STORE_KEY, "home");
				listFragment.setArguments(bundle);
				return listFragment;
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return TITLE.length;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			// TODO Auto-generated method stub
			if(position==3){
				return getResources().getString(R.string.newest_title);
			}else
			return TITLE[position];
		}
		
		@Override
		public void setPrimaryItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			if(position > 1){
				HomeListFragment frag = (HomeListFragment) object;
				frag.init();
			}else if(position==0){
				CategoryFragment catFrag = new CategoryFragment();
				Bundle b = new Bundle();
				b.putString(Constants.STORE_KEY, "apps");
				catFrag.setArguments(b);
			}
		}
	}
	public static class InstalledAppItem {
		public String getPackageName() {
			return packageName;
		}
		public String getVersion() {
			return version;
		}
		private String packageName;
		private String version;
		public InstalledAppItem(String packageName, String version) {
			this.packageName = packageName;
			this.version = version;
		}
		
	}
	@Override
	public void onDownloadComplete(String path) {
		// TODO Auto-generated method stub
		Utils.installAPK(this, path);
		finish();
	}

	@Override
	public void onDownloadError() {
		AlertDialog.Builder builder=new Builder(this);
		builder.setMessage(R.string.couldntdownloadnewversion).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		}).create().show();
	}
	
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		return cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
	}
	
//	private Response.Listener<JSONObject> getVolleySuccessListener(){
//		  return new Response.Listener<JSONObject>() {
//		   @Override
//		   public void onResponse(JSONObject response) {
//		    // TODO Auto-generated method stub
//		    System.err.println(response.toString());
//		    try {
//		     boolean status = response.getBoolean("status");
//		     
//		    } catch (JSONException e) {
//		     e.printStackTrace();
//		    }
//		   }
//		  };
//		 }
//	private Response.ErrorListener getVolleyErrorListener(){
//		  return new Response.ErrorListener() {
//		   @Override
//		   public void onErrorResponse(VolleyError error) {
//		    // TODO Auto-generated method stub
//			   if(error!=null)
//		    Log.e("error listener","error listener: "+error.getMessage());
//		   }
//		  };
//		 }
//	public class GetTopAsync extends AsyncTask<Void, Void, String>{
//		private String type,version,isTablet;
//		private int cateId,storeId,start;
//		
//		public GetTopAsync(String type, String version,
//				String isTablet, int cateId, int storeId, int start) {
//			super();
//			this.type = type;
//			this.version = version;
//			this.isTablet = isTablet;
//			this.cateId = cateId;
//			this.storeId = storeId;
//			this.start = start;
//		}
//		@Override
//		protected String doInBackground(Void... params) {
//			return HttpHelper.getTopContent(type, cateId, "03cea4ee604e07b241c4c097feae3274", storeId, start, version,  isTablet);
//		}
//		@Override
//		protected void onPostExecute(String result) {
//			Log.e("getTopAsync","getTopAsync: "+result);
//		}
//	}
	public void onEventMainThread(GetTorStatusEvent event){
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
		((AppStoreVnApplication)getApplication()).enableTor=event.status;
	}
	
	public void onEventMainThread(GetEnaCStatusEvent event){
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
		SharedPreferences shared= getSharedPreferences("system_pre", MODE_PRIVATE);
		if(event.status){
			shared.edit().putBoolean(Constants.ENABLE_GUEST, false).commit();
		}else{
			shared.edit().putBoolean(Constants.ENABLE_GUEST, true).commit();
		}
		checkUpdateDaily();
	}
	
	public void onEventMainThread(RequestUpdateFailEvent event){
		if(event.getErrorCode() == -101){
			AlertDialogManager am = new AlertDialogManager(this);
			am.showPositiveDialog(R.string.couldnot_retrieve_data, R.string.retry, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					checkForUpdate();
				}
			});
		}
		else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showPositiveDialog(R.string.error, R.string.retry, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					checkForUpdate();
				}
			});
		}
	}
	
	private void checkForUpdate(){
		Log.e("checkForUpdate","cfu");
		String deviceStatus;
		apptoko.com.util.RootUtil root = new apptoko.com.util.RootUtil();
		isRooted = root.isDeviceRooted();
		((AppStoreVnApplication)getApplication()).setRooted(isRooted);
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putBoolean(Constants.IS_ROOTED, isRooted).commit();
		if(isRooted){
			deviceStatus = "1";
		} else {
			deviceStatus = "0";
		}
		if(progressLoading!=null&&!progressLoading.isShowing()){
			progressLoading.show();
		}
		
		bgTask.checkClientUpdate(deviceStatus,false);
	}
	
	private void checkTor(){
		bgTask.checkTor();
	}
	private void getLA(){
		locationResult = new LocationResult(){
		    @Override
		    

		        public void gotLocation(Location location){
//		    	Toast.makeText(NewsFeedActivity.this, location.get, duration);
				try {
					Geocoder geocoder = new Geocoder(HomeActivity.this,
							Locale.ENGLISH);
					List<Address> addresses = geocoder.getFromLocation(
							location.getLatitude(), location.getLongitude(), 2);
					String add = "";
					if (addresses != null) {
						add = addresses.get(0).getCountryCode();
						Toast.makeText(HomeActivity.this, add,
								Toast.LENGTH_LONG).show();
//						for (int j = 0; j < 2; j++) {
//							Address returnedAddress = addresses.get(j);
//							StringBuilder strReturnedAddress = new StringBuilder();
//							for (int i = 0; i < returnedAddress
//									.getMaxAddressLineIndex(); i++) {
//								strReturnedAddress.append(
//										returnedAddress.getCountryCode());
//							}
//							add += strReturnedAddress.toString() + " | ";
//						}
					}else{
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								AlertDialog.Builder builder=new Builder(HomeActivity.this);
								builder.setMessage("Unexpected problem, exit app..").setPositiveButton("Exit", new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										dialog.dismiss();
										finish();
									}
								}).show();
							}
						});
						return;
					}
					getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.COUNTRY_CODE, add).commit();
					checkTor();
					checkForUpdate();
					Log.e("LA","LA:"+add);
				} catch (Exception ex) {
					ex.printStackTrace();
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							AlertDialog.Builder builder=new Builder(HomeActivity.this);
							builder.setMessage("Unexpected problem, exit app..").setPositiveButton("Exit", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									finish();
								}
							}).show();
						}
					});
				}
		    }
		};
		new GetLAAsync().execute();
	}
	LocationResult locationResult;
	HttpLa myLocation = new HttpLa();
	public class GetLAAsync extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {

			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			myLocation.getLocation(HomeActivity.this, locationResult);
		}
		
	}
}
